<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    <style>

        #manage_user_tb {
            height: 50px;
            background: #CC2222;
        }
    </style>
</head>
<body>
<div id="manage_user_tb" style="padding:5px;height:auto;background-color:#CCE6FF;text-align: center">
    <div>
        <form id="manageUserFrom">
            姓名<span class="fa fa-user-circle fa-fw"  style="color: orangered"></span><input class="easyui-textbox" name="userName">
            账户<span class="fa fa-user-circle-o fa-fw"></span><input class="easyui-textbox" name="userCode">
            用户组织 <i class="fa fa-object-ungroup fa-fw" aria-hidden="true"></i>
            <select class="easyui-combobox" name="pkOrg" panelHeight="auto" style="width: 180px">
                <option value=""></option>
                <option value="0001O110000000001HET">澳宝化妆品（惠州）有限公司</option>
                <option value="0001O110000000001HGC">惠州兆婷化妆品有限公司</option>
                <option value="0001O110000000001HC5">澳寶化粧品（香港）有限公司</option>
            </select>
            职位<span class="fa fa-address-book-o fa-fw" style="color: green" aria-hidden="true"></span>
            <select class="easyui-combobox" name="userPosition" panelHeight="auto" style="width: 100px">
                <option value=""></option>
                <option value="0">员工</option>
                <option value="1">项目经理</option>
                <option value="2">部门经理</option>
                <option value="3">总经理</option>
                <option value="4">总裁</option>
                <option value="5">内销会计</option>
                <option value="6">外销会计</option>
                <option value="7">财务经理</option>
                <option value="8">成本财务</option>
                <option value="9">副总经理</option>
                <option value="10">业务部文员</option>
                <option value="999">系统管理员</option>
            </select>
            <a href="#" class="easyui-linkbutton" onclick="queryConditionUser()" iconCls="icon-search">查询</a>
        </form>
    </div>
    <!-- 分配菜单窗口的按钮 -->
    <div id="manage_user_menu_btn" style="padding: 5px 15px 5px 0px;text-align: right;display: none">
        <a class="easyui-linkbutton" data-options="iconCls:'icon-ok'" onclick="submitRoleMenu()">提交</a>
        <a class="easyui-linkbutton" onclick="$('#manage_user_menu').dialog('close')">取消</a>
    </div>
</div>
<table id="manage_user"></table>


<script th:inline="none" type="text/javascript">
    //根据条件刷新表
    function queryConditionUser() {
        $("#manageUserFrom").f
        //console.log("数据：",$("#manageUserFrom").serialize())
        manageUserDatagridInit("/manage/user/selectConditionUser?" + $("#manageUserFrom").serialize());
    }

    //所有部门的信息，用于格式化显示部门
    var manageUserDatagridDeptformatterAllData = commonAjax("post", "/manage/dept/getAllOpalDept", {})
    //打开页面初始化用户表
    manageUserDatagridInit('/manage/user/selectConditionUser')


    //用户表初始化方法
    function manageUserDatagridInit(url) {
        $('#manage_user').edatagrid({
            autoSave: true,
            height: costsystemFblH,
            pagination: true,
            pageSize: 20,
            pageList: [10, 20, 30],
            url: url,
            striped: true,
            fitColumns: true,
            rownumbers: true,
            nowrap: false,
            columns: [[
                {field: 'userId', title: 'id', hidden: true},
                {
                    field: 'userName',
                    title: '姓名',
                    width: 40,
                    align: 'center',
                    editor: {type: 'textbox', options: {required: true}}
                },
                {
                    field: 'userCode',
                    title: '账户',
                    width: 60,
                    align: 'center',
                    editor: {type: 'textbox', options: {required: true}}
                },
                {
                    field: 'userMail',
                    title: '邮箱',
                    width: 70,
                    align: 'center',
                    editor: {type: 'textbox', options: {required: true}}
                },
                {
                    field: 'pkOrg',
                    title: '用户组织',
                    align: 'center',
                    width: 100,
                    formatter: function (value, row, index) {
                        switch (value) {
                            case "0001O110000000001HET":
                                value = "【澳宝化妆品（惠州）有限公司】<br>";
                                break;
                            case "0001O110000000001HC5":
                                value = "【澳寶化粧品（香港）有限公司】<br>";
                                break;
                            case "0001O110000000001HGC":
                                value = "【惠州兆婷化妆品有限公司】<br>";
                                break;
                            case "0001O110000000001HJE":
                                value = "【品木丝序园林绿化建筑工程（惠州）有限公司】<br>";
                                break;
                            case "0001O110000000001HHM":
                                value = "【澳寶國際貿易有限公司】<br>";
                        }
                        return value;
                    },
                    editor: {type: 'combobox', options: {required: true, valueField: 'pkhrorg', textField: 'name'}}
                },
                {
                    field: 'userDept',
                    title: '部门',
                    align: 'center',
                    width: 80,
                    formatter: function (value, row, index) {
                        var resultDept = "";
                        manageUserDatagridDeptformatterAllData.forEach(function (val) {
                            if (val.pkDept == value) {
                                resultDept = val.name
                                return;
                            }
                        })
                        return resultDept;
                    },
                    editor: {type: 'combotree', options: {required: true, valueField: 'id', textField: 'text'}}
                },
                {
                    field: 'userPosition',
                    title: '职位',
                    align: 'center',
                    width: 50,
                    formatter: function (value, row, index) {
                        //console.log("职位",value)
                        //console.log("职位",typeof(value))
                        value = Number(value)
                        var userPosition;
                        switch (value) {
                            case 0:
                                userPosition = "员工"
                                break;
                            case 1:
                                userPosition = "项目经理"
                                break;
                            case 2:
                                userPosition = "部门经理"
                                break;
                            case 3:
                                userPosition = "总经理"
                                break;
                            case 4:
                                userPosition = "总裁"
                                break;
                            case 5:
                                userPosition = "内销会计"
                                break;
                            case 6:
                                userPosition = "外销会计"
                                break;
                            case 7:
                                userPosition = "财务经理"
                                break;
                            case 8:
                                userPosition = "成本财务"
                                break;
                            case 9:
                                userPosition = "副总经理"
                                break;
                            case 10:
                                userPosition = "业务部文员"
                                break;
                            case 999:
                                userPosition = "系统管理员"
                                break;
                        }
                        return userPosition;
                    },
                    editor: {
                        type: 'combobox', options: {
                            required: true,
                            valueField: 'userPosition', textField: 'userPositionName', data: [
                                {userPosition: 0, userPositionName: '员工'},
                                {userPosition: 1, userPositionName: '项目经理'},
                                {userPosition: 2, userPositionName: '部门经理'},
                                {userPosition: 3, userPositionName: '总经理'},
                                {userPosition: 4, userPositionName: '总裁'},
                                {userPosition: 5, userPositionName: '内销会计'},
                                {userPosition: 6, userPositionName: '外销会计'},
                                {userPosition: 7, userPositionName: '财务经理'},
                                {userPosition: 8, userPositionName: '成本财务'},
                                {userPosition: 9, userPositionName: '副总经理'},
                                {userPosition: 10, userPositionName: '业务部文员'},
                                {userPosition: 999, userPositionName: '系统管理员'}
                            ]
                        }
                    }
                },
                {
                    field: 'hrorgPkhrorg',
                    title: '权限组织',
                    width: 100,
                    align: 'center',
                    formatter: function (value, row, index) {
                        if (value) {
                            var values = "";
                            var vars = value.split(",");
                            for (var i = 0; i < vars.length; i++) {

                                switch (vars[i]) {
                                    case "0001O110000000001HET":
                                        values += "【澳宝化妆品（惠州）有限公司】<br>";
                                        break;
                                    case "0001O110000000001HC5":
                                        values += "【澳寶化粧品（香港）有限公司】<br>";
                                        break;
                                    case "0001O110000000001HGC":
                                        values += "【惠州兆婷化妆品有限公司】<br>";
                                        break;
                                    case "0001O110000000001HJE":
                                        values += "【品木丝序园林绿化建筑工程（惠州）有限公司】<br>";
                                        break;
                                    case "0001O110000000001HHM":
                                        values += "【澳寶國際貿易有限公司】<br>";
                                }
                            }
                            return values;
                        }
                    },
                    editor: {
                        type: 'combobox', options: {
                            multiple: true, url: '/manage/user/selectallhrorg',
                            valueField: 'pkhrorg', textField: 'name'
                        }
                    }
                },
                {
                    field: 'userPassword',
                    title: '密码',
                    width: 80,
                    align: 'center',
                    editor: {type: 'textbox', options: {prompt: '不修改密码不用填写'}}
                }
            ]],
            onLoadSuccess: function (data) {
                if (data.statu == 404) {
                    warnSessionConfirm();
                }
            },
            onAdd: function (index, row) {
                manageUserAddAndEdit(index, row)
            },
            onEdit: function (index, row) {
                manageUserAddAndEdit(index, row)
            },
            onSave: function (index, row) {
                if (row.statu == 200) {
                    //刷新表
                    manageUserDatagridInit("/manage/user/selectConditionUser?" + $("#manageUserFrom").serialize());
                }
                layer.msg(row.message)
            },
            saveUrl: "/manage/user/addUser",
            updateUrl: "/manage/user/updateuser",
            toolbar: [
                {
                    text: '添加', iconCls: 'icon-add', handler: function () {
                        $('#manage_user').edatagrid('addRow', 0)
                    }
                },
                {
                    text: '保存', iconCls: 'icon-save', handler: function () {
                        $('#manage_user').edatagrid('saveRow')
                    }
                },
                {
                    text: '删除', iconCls: 'icon-remove',
                    handler: function () {
                        //获取选中的行
                        var userRows = $('#manage_user').datagrid('getSelections');
                        if (userRows.length > 0) {
                            $.messager.confirm('确认', '您确认想要删除<span style="color:red;">' + userRows[0].userName + '</span>用户吗？', function (r) {
                                if (r) {
                                    $.post({
                                        url: '/manage/user/deleteuser',
                                        data: JSON.stringify(userRows),
                                        contentType: 'application/json',
                                        success: function (data) {
                                            windowsOperation(null, "manage_user", data);
                                        }
                                    })
                                }
                            });
                        } else {
                            topCommonMessage('选择您想要删除的用户！');
                        }
                    }
                }, {
                    text: '分配角色', iconCls: 'icon-ok',
                    handler: function () {
                        //获取选中的行
                        var userRows = $('#manage_user').datagrid('getSelections');
                        if (userRows.length != 1) {
                            layer.msg("请选择一位用户来更新角色！")
                            return
                        }
                        //往自己元素后面添加
                        $('#manage_user').after("<div id='manageUserRole'></div>");
                        $("#manageUserRole").dialog({
                            title: '分配角色',
                            width: 400,
                            height: 500,
                            content: "<div id='manageUserRoleCombotree'></div>",
                            onOpen: function () {
                                //初始化true，并赋值当前用户的角色
                                manageUserRoleCombotreeInit(userRows[0].userId);
                            },
                            onClose: function () {
                                //从浏览器中清除
                                $("#manageUserRole").remove();

                            },
                            buttons: [{
                                text: '提交',
                                handler: function () {
                                    //获取当前树选中的节点:id、text
                                    var nodes = $('#manageUserRoleCombotree').tree('getChecked');
                                    var roleIds = [];
                                    nodes.forEach(function (val) {
                                        roleIds.push(val.id)
                                    })
                                    //根据选中的用户id修改角色id

                                    $.post({
                                        contentType: "application/json;charset=utf-8",
                                        url: "/manage/user/updateByUserIdRole",
                                        data: JSON.stringify({userId: userRows[0].userId, roleIds: roleIds}),
                                        success: function (data) {
                                            layer.msg(data.message)
                                            if (data.statu == 200) {
                                                //关闭角色框
                                                $("#manageUserRole").dialog("close")
                                                //更新菜单
                                                loadTree();
                                            }
                                        }
                                    })

                                }
                            }]
                        })
                        $("#manageUserRole").dialog('center')
                    }
                },
                {text:'分配菜单',iconCls:'icon-ok',
                    handler:function(){
                        var userRows = $('#manage_user').datagrid('getSelections');
                        if (userRows.length != 1) {
                            layer.msg("请选择一位用户来更新菜单！")
                            return
                        }
                       var  content='<ul id="manage_user_menu_ul" class="easyui-tree"></ul>'
                        //往自己元素后面添加
                        $('#manage_user').after("<div id='manage_user_menu'></div>");
                        $("#manage_user_menu").append(content)
                        $("#manage_user_menu_ul").tree({
                            method:'post',
                            url:'/manage/menu/getAllMenu',
                            checkbox:true
                        })
                        $("#manage_user_menu").dialog({
                            title:'分配菜单【'+userRows[0].userName+'】',
                            closed:false,
                            cache:false,
                            width:400,
                            height:500,
                            buttons:'#manage_user_menu_btn',
                            modal:true,
                            onOpen:function () {
                                var nodes = $("#manage_user_menu_ul").tree('getChecked');
                                $.ajax({
                                    url: '/manage/menu/getOpalMenuByUserId',
                                    data: {userId: userRows[0].userId},
                                    // async:false,
                                    method: 'post',
                                    dataType:'json',
                                    success: function (m) {
                                        if (m.statu == 404) {
                                            $.messager.confirm('系统提示', '登录已过期，要为您转回登录界面吗?', function (c) {
                                                if (c) {
                                                    northLogout();
                                                }
                                            })
                                        }
                                        for(var j = 0; m.length>j; j++) {
                                            //获取节点：使用node.target转化为节点对象
                                            var node = $("#manage_user_menu_ul").tree('find', m[j].id);
                                           // 若不是叶子节点的话(叶子节点可认为是文件，不是叶子节点证明是目录)进行选中会造成它下面所有的都会被选中
                                            if(node !=null){
                                                //判断是否叶子节点
                                                if ($("#manage_user_menu_ul").tree('isLeaf', node.target)) {
                                                    //选中是叶子节点
                                                    $("#manage_user_menu_ul").tree('check', node.target);
                                                }
                                            }
                                        }

                                    }
                                })
                            },
                            onClose:function () {
                                $("#manage_user_menu").remove()
                            }
                        })

                    }

                }]

        });
    }

    //角色树的初始化
    function manageUserRoleCombotreeInit(userId) {
        $("#manageUserRoleCombotree").tree({
            checkbox: true,
            url: '/manage/role/selectallrole2',
            onLoadSuccess: function (node, data) { //加载成功的事件
                //根据用户的id获取用户的角色id
                var userRoleIds = commonAjax("get", "/manage/user/findByUserIdRole", {'userId': userId})
                //双重循环判断
                data.forEach(function (value) {
                    var id = value.id;//角色id
                    userRoleIds.forEach(function (roleId) {
                        if (id == roleId) {
                            var node = $('#manageUserRoleCombotree').tree('find', id);
                            $('#manageUserRoleCombotree').tree("check", node.target)
                        }
                    })
                })
            }
        })
    }

    function manageUserAddAndEdit(index, row) {
        //部门的jquery对象
        var userDept = $('#manage_user').datagrid("getEditor", {index: index, field: 'userDept'}).target;
        //用户组织
        var pkOrg = $('#manage_user').datagrid("getEditor", {index: index, field: 'pkOrg'}).target;
        pkOrg.combobox({
            url: '/manage/user/selectallhrorg',
            onChange: function (newVal, oldVal) { //组织刷新部门
                if (newVal) {
                    userDept.combotree({
                        url: '/manage/dept/getDeptEasyUiTreeData?pkOrg=' + newVal,
                        onLoadSuccess: function (node, data) {//数据加载成功后触发
                            userDept.combotree("setValue", row.userDept)
                        }
                    })
                }

            },
            onLoadSuccess: function (node, data) {//数据加载成功后触发
                pkOrg.combobox("setValue", row.pkOrg)//设置默认值
            }
        })
        //用户密码：清空
        var userPassword = $('#manage_user').datagrid("getEditor", {
            index: index,
            field: 'userPassword'
        }).target.textbox("setValue", "");
    }

    //分配权限
    function submitRoleMenu(){
        var row=$('#manage_user').datagrid("getSelected");
        if (row==null){
            return;
        }

        //定义数组：封装树中全选中的
        var menuIds=new Array();

        //级联有全选中和半选中【indeterminate】
        $($("#manage_user_menu_ul").tree("getChecked",['checked','indeterminate'])).each(function (i,node) {
            menuIds[i]=node["id"];
        })

        $.ajax({
            url: '/manage/menu/updateMenuPermission',
            data:{userId:row.userId,menuIds:menuIds},
            method: 'post',
            dataType: 'json',
            success:function (r) {
                if (r.statu==404){
                    warnSessionConfirm();
                }else{
                    loadTree();
                    windowsOperation("manage_user_menu",null, r);
                }
            }
        })
    }

</script>
</body>
</html>